import { UniAdapter } from 'uniapp-axios-adapter'
import axios from 'axios'
import { getToken } from '@weWork/utils/token'

export const getHttp = (host: string, envHost: string) => {
  const { DEV } = import.meta.env

  const baseURL = DEV ? envHost : host

  const request = axios.create({
    baseURL,
    timeout: 10000,
    adapter: UniAdapter
  })

  request.interceptors.request.use((config) => {
    if (config.headers) {
      //带上token
      config.headers['Authorization'] = getToken()
    }

    return config
  })

  request.interceptors.response.use((response) => {
    // 统一处理响应,返回Promise以便链式调用
    if (response.status === 200) {
      const { data } = response
      if (data && data.code === 200) {
        return Promise.resolve(data)
      } else {
        return Promise.reject(data)
      }
    } else {
      return Promise.reject(response)
    }
  })
  return request
}
